const cloud = require('wx-server-sdk');
cloud.init({
  env:"xiaotiao-6gcr9hxy3d8aa90f"
});
const db = cloud.database();
const _ = db.command;
exports.main = async (event, context) => {
  var openid = event.openid;
  var myrecords = event.records;
  var mytotalday = event.totalday;
  return await db.collection("records").where({
    _openid:openid,
  }).get().then(res=>{
    if(res.data.length ==0){
      console.log("找不到openid")
      db.collection("records")
      .add({
        data:{
          _openid:openid,
          alcohol:0,
          diet:0,
          emotion:0,
          encourage:0,
          remind:0,
          sleep:0,
          sport:0,
          totalday:0
        }
      })
    }
    db.collection("records")
    .where({
      _openid:openid
    }).get().then(res=>{
        var allAlcohol = myrecords.map(e=>e._alcohol).filter(e=>e!=null&&e==1)
        console.log(allAlcohol)

        var allDiet = myrecords.map(e=>e._diet).filter(e=>e!=null&&e==1)
        console.log(allDiet)

         var allEmotion = myrecords.map(e=>e._emotion).filter(e=>e!=null&&e==1)
         console.log(allEmotion)

         var allSleep = myrecords.map(e=>e._sleep).filter(e=>e!=null&&e==1)
         console.log(allSleep)

         var allSport = myrecords.map(e=>e._sport).filter(e=>e!=null&&e==1)
         console.log(allSport)
          
      var newAlcohol = allAlcohol.length
      console.log(newAlcohol)
      var newDiet = allDiet.length
      console.log(newDiet)
      var newEmotion = allEmotion.length
      console.log(newEmotion)
      var newSleep = allSleep.length
      console.log(newSleep)
      var newSport = allSport.length
      console.log(newSport)
      var newTotalDay = mytotalday
      console.log(newTotalDay)
      db.collection("records")
      .where({
        _openid:openid
      }).update({
        data:{
          alcohol:newAlcohol,
          diet:newDiet,
          emotion:newEmotion,
          sleep:newSleep,
          sport:newSport,
          totalday:newTotalDay
        }
      }).then(res=>{
        console.log("更新成功哇")
      }).catch(res=>{
        console.log("更新失败")
      })
    })
    .catch(error=>{
      console.log("出错啦")
    })
    // update({
    //   data:{
    //     alcohol:alcohol
    //   }
    // })
  })
}